import pygame
import pymunk
import sys
import random


gravity_x = 0.0
gravity_y = 0.0
space = pymunk.Space()
space.gravity = (gravity_x, gravity_y)

size = width, height = 640, 480
ball_radius = 10
ball_mass = 10




def to_pygame(p):
    """Convert position of pymunk to position of pygame"""
    return int(p.x), int(-p.y + height)


def to_pymunk(x, y):
    """Convert position of pygame to position of pymunk"""
    return (x, -(y - height))

class Hewoef():
    def post_solve_left_line12333(arbiter, sp, data):
        move = move * -1
        hew.sef = 123

    #def post_solve_left_line(arbiter, sp, data):
    #     height *= -1

    def post_solve_top_line(arbiter, sp, data):
        x, y = space.gravity
        space.gravity = (x, -y)

move = {"x123": 1, "y123": 23}
move_x = random.randint(1, 30)
move_y = random.randint(1, 30)

hew = Hewoef()

# 创建边框
borders = [
    pymunk.Segment(space.static_body, (0.0, 0.0), (0.0, height), 0.0),
    pymunk.Segment(space.static_body, (0.0, height), (width, height), 0.0),
    pymunk.Segment(space.static_body, (width, height), (width, 0.0), 0.0),
    pymunk.Segment(space.static_body, (width, 0.0), (0.0, 0.0), 0.0)
]

collision_type = 1
for line in borders:
    line.elasticity = 0.95
    line.friction = 1
    line.collision_type = collision_type
    space.add(line)
    collision_type += 1

# 创建Ball
ball_moment = pymunk.moment_for_circle(ball_mass, 0, ball_radius, (0, 0))
ball_body = pymunk.Body(ball_mass, ball_moment)
ball_body.position = (width / 2, height / 2)
ball = pymunk.Circle(ball_body, ball_radius)
ball.collision_type = 5
ball.elasticity = 0.9999999
space.add(ball_body, ball)





#space.add_collision_handler(5, 1).post_solve = post_solve_left_line
#space.add_collision_handler(5, 2).post_solve = post_solve_top_line
#space.add_collision_handler(5, 3).post_solve = post_solve_left_line
#space.add_collision_handler(5, 4).post_solve = post_solve_top_line

# 初始化 pygame
pygame.init()
screen = pygame.display.set_mode(size)
color = (0, 0, 0)

ball_img = pygame.image.load("../res/image/poke-ball-small.png")
ball_rect = ball_img.get_rect()
clock = pygame.time.Clock()
while True:
    clock.tick(30)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    ### Update physics
    #fps = 50
    #iterations = 1
    #dt = 1.0 / float(fps) / float(iterations)
    #for x in range(iterations):  # 10 iterations to get a more stable simulation
    #    space.step(dt)
    space.step(0.01)
    ball_rect = ball_rect.move(move_x, move_y)
    # print("MOVE: x: {}, y:{}".format(move_x, move_y))

    ball_body.position = to_pymunk(ball_rect.x, ball_rect.y)
    print("x: {}, y:{}".format(ball_rect.x, ball_rect.y))

    screen.fill(color)
    screen.blit(ball_img, ball_rect)
    pygame.display.flip()
